package com.example.community.service;

import com.example.community.dao.LoginTicketMapper;
import com.example.community.dao.UserMapper;
import com.example.community.entity.LoginTicket;
import com.example.community.entity.User;
import com.example.community.util.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Author: huang
 * @Date: 2021/9/13 21:08
 * @Description:
 */
@Service
public class UserService implements CommunityConstant {

    /*@Autowired
    private LoginTicketMapper loginTicketMapper;*/

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MailClient mailClient;

    //生成html的，模板引擎
    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private RedisTemplate redisTemplate;

    //发送的激活码得包含域名和项目名
    //项目域名
    @Value("${community.path.domain}")
    private String domain;

    //项目名
    @Value("${server.servlet.context-path}")
    private String contextPath;

    public User findUserById(int userId) {
        //return userMapper.selectById(userId);
        User user = getCache(userId);
        if (user == null) {
            user = initCache(userId);
        }
        return user;
    }

    //因为密码，用户名，邮箱都可能为空，返回的信息不一样，我们呢用Map存储不同的信息
    public Map<String, Object> register(User user) {
        Map<String, Object> map = new HashMap<>();

        //空值处理
        if (user == null) {
            throw new IllegalArgumentException("参数不能为空！");
        }
        if (StringUtils.isBlank(user.getUsername())) {
            map.put("usernameMsg", "账号不能为空！");
            return map;
        }
        if (StringUtils.isBlank(user.getPassword())) {
            map.put("passwordMsg", "密码不能为空！");
            return map;
        }
        if (StringUtils.isBlank(user.getEmail())) {
            map.put("emailMsg", "邮箱不能为空！");
            return map;
        }

        //从数据库验证用户是否存在
        User u = userMapper.selectByName(user.getUsername());
        if (u != null) {
            //账号存在
            map.put("usernameMsg", "该账号已存在！");
            return map;
        }
        //从数据库验证邮箱是否存在
        u = userMapper.selectByEmail(user.getEmail());
        if (u != null) {
            //邮箱存在
            map.put("emailMsg", "该邮箱已被注册！");
            return map;
        }

        //注册用户,添加到数据库
        user.setSalt(CommunityUtil.generateUUID().substring(0,5));
        user.setPassword(CommunityUtil.md5(user.getPassword() + user.getSalt()));
        user.setType(0);//初始时都是普通用户
        user.setStatus(0);//激活状态
        user.setActivationCode(CommunityUtil.generateUUID());
        user.setHeaderUrl(String.format("https://api.multiavatar.com/%d.png", new Random().nextInt(10000)));
        user.setCreateTime(new Date());
        userMapper.insertUser(user);

        //给用户发送html激活邮件
        Context context = new Context();
        context.setVariable("email", user.getEmail());
        // http://localhost:8080/community/activation/101/code
        String url = domain + contextPath + "/activation/" + user.getId() + "/" + user.getActivationCode();
        context.setVariable("url", url);
        String content = templateEngine.process("/mail/activation", context);
        mailClient.sendMail(user.getEmail(), "唠嗑论坛激活账号", content);

        return map;
    }

    //激活处理
    public int activation(int userId, String code) {
        User user = userMapper.selectById(userId);
        if (user.getStatus() == 1) {
            //已经激活
            return ACTIVATION_REPEAT;
        }else if (user.getActivationCode().equals(code)) {
            //激活码相同，激活成功，修改用户的状态置为1
            userMapper.updateStatus(userId,1);
            clearCache(userId);
            return ACTIVATION_SUCCESS;
        }else {
            return ACTIVATION_FAILURE;
        }
    }

    /**
     *
     * @param username
     * @param password
     * @param expiredSeconds
     * @return 返回值使用map返回多种情况的消息，需要浏览器传用户名，密码，过期时间。
     * 首先对空值处理，以防浏览器错误传入空值
     * 通过用户名查出user，依次验证账号，账号状态，密码
     * 验证通过后生成登录凭证，存到数据库，并返回ticket
     */
    public Map<String, Object> login(String username, String password, int expiredSeconds) {
        Map<String, Object> map = new HashMap<>();

        //空值处理
        if (StringUtils.isBlank(username)) {
            map.put("usernameMsg", "账号不能为空!");
            return map;
        }
        if (StringUtils.isBlank(password)) {
            map.put("passwordMsg", "密码不能为空!");
            return map;
        }

        //验证登录账号的合法性
        //1.登录账号是否存在
        User user = userMapper.selectByName(username);
        if (user == null) {
            map.put("usernameMsg", "该账号不存在!");
            return map;
        }

        //2.验证用户的状态是否激活
        if (user.getStatus() == 0) {
            map.put("usernameMsg", "该账号未激活!");
            return map;
        }

        //3.验证密码是否正确，由于我们在数据库存入的是加密的密码，所以我们需要给当前传入的密码进行加密，才能判断密码的正确性
        password = CommunityUtil.md5(password + user.getSalt());
        if (!user.getPassword().equals(password)) {
            map.put("passwordMsg", "密码不正确!");
            return map;
        }

        //4.生成登陆凭证存到数据库，并传给客户端ticket。相当于cookie、session
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setUserId(user.getId());
        loginTicket.setStatus(0);//0代表凭证有效
        loginTicket.setTicket(CommunityUtil.generateUUID());
        loginTicket.setExpired(new Date(System.currentTimeMillis() + expiredSeconds * 1000));
        //loginTicketMapper.insertLoginTicket(loginTicket);
        String redisKey = RedisKeyUtil.getTicket(loginTicket.getTicket());
        redisTemplate.opsForValue().set(redisKey, loginTicket);


        //5.把登录凭证传给客户端
        map.put("ticket", loginTicket.getTicket());
        return map;
    }

    //退出登录
    public void logout(String ticket) {
        //loginTicketMapper.updateStatus(ticket, 1);
        String redisKey = RedisKeyUtil.getTicket(ticket);
        LoginTicket loginTicket = (LoginTicket) redisTemplate.opsForValue().get(redisKey);
        loginTicket.setStatus(1);
        redisTemplate.opsForValue().set(redisKey,loginTicket);
    }

    /**
     *
     * @param ticket
     * @return  从Redis取值，强转成 loginTicket 类，将登录凭证的状态修改为1，然后重新传入Redis里。
     */
    public LoginTicket findLoginTicket(String ticket) {
        //return loginTicketMapper.selectByTicket(ticket);
        String redisKey = RedisKeyUtil.getTicket(ticket);
        return (LoginTicket) redisTemplate.opsForValue().get(redisKey);
    }

    public int updateHeader(int userId, String headerUrl) {
        //return userMapper.updateHeader(userId, headerUrl);
        int rows = userMapper.updateHeader(userId, headerUrl);
        clearCache(userId);
        return rows;
    }


    public Map<String, Object> updatePassword(User user, String originalPassword, String newPassword, String confirmPassword) {
        Map<String, Object> map = new HashMap<>();
        //空值判断
        if (StringUtils.isBlank(originalPassword)) {
            map.put("originalPasswordMsg", "原密码不能为空!");
            return map;
        }
        if (StringUtils.isBlank(newPassword)) {
            map.put("newPasswordMsg", "新密码不能为空!");
            return map;
        }
        if (StringUtils.isBlank(confirmPassword)) {
            map.put("confirmPasswordMsg", "确认密码不能为空!");
            return map;
        }

        //判断输入的原密码是否正确 && 判断原密码是否与新密码一样
        String password = user.getPassword();
        //对输入的原密码进行加密判断
        originalPassword = CommunityUtil.md5(originalPassword + user.getSalt());
        if (!password.equals(originalPassword)) {
            map.put("originalPasswordMsg", "原密码不正确!");
            return map;
        }
        if (password.equals(originalPassword)) {
            map.put("newPasswordMsg", "新密码不能与原密码一样!");
            return map;
        }

        //判断新密码与确认密码是否一样,也要对密码进行加密
        newPassword = CommunityUtil.md5(newPassword + user.getSalt());
        confirmPassword = CommunityUtil.md5(confirmPassword + user.getSalt());
        if (!newPassword.equals(confirmPassword)) {
            map.put("errorMsg", "两次输入的密码不一致!");
            return map;
        }
        userMapper.updatePassword(user.getId(), newPassword);
        clearCache(user.getId());
        map.put("rightMsg", "修改成功");
        return map;
    }

    public User findUserByName(String username) {
        return userMapper.selectByName(username);
    }

    //1.优先从缓存中取用户信息
    private User getCache(int userId) {
        String redisKey = RedisKeyUtil.getUser(userId);
        return (User) redisTemplate.opsForValue().get(redisKey);
    }

    //2.从缓存中取不到时，初始化用户缓存数据
    private User initCache(int userId) {
        User user = userMapper.selectById(userId);
        String redisKey = RedisKeyUtil.getUser(userId);
        redisTemplate.opsForValue().set(redisKey, user, 3600, TimeUnit.SECONDS);
        return user;
    }

    //3.用户修改信息后清除缓存数据
    private void clearCache(int userId) {
        String redisKey = RedisKeyUtil.getUser(userId);
        redisTemplate.delete(redisKey);
    }

    /**
     *  查询某用户的权限
     * @param userId
     * @return  根据用户userid查询type，type=1是管理员，2是版主， 3是普通用户。返回的是 GrantedAuthority类的集合
     */
    public Collection<? extends GrantedAuthority> getAuthorities(int userId) {
        User user = this.findUserById(userId);

        List< GrantedAuthority> list = new ArrayList<>();
        list.add(new GrantedAuthority() {
            @Override
            public String getAuthority() {
                switch (user.getType()) {
                    case 1:
                        return AUTHORITY_ADMIN;
                    case 2:
                        return AUTHORITY_MODERATOR;
                    default:
                        return AUTHORITY_USER;
                }
            }
        });
        return list;
    }

}
